<?php

/*
 * 标题：阿里紫订单管理系统
 * 作者：忆天网络 QQ715457186 
 * 官方网址：www.fjd100.com||www.yi66.net
 */


class OrderAction extends AliziAction {
	public function _initialize(){
        parent::_init();
    }
	function index($payment=0){
	
		if(isset($_GET['do'])){
			$this->view($_GET['id']);exit;
		}
		$field = "*";//"id,order_no,item_name,quantity,total_price,name,mobile,payment,delivery_name,delivery_no,user_pid,seller_id,remark,add_time";
		$Model = M('Order');
		$fields = trim($_GET['fields']);
		$status = $_GET['status'];
		$payment = $_GET['payment'];
		$keyword = trim($_GET['keyword']);
		$category_id = intval($_GET['category_id']);
		$time_start = strtotime($_GET['time_start']);
		$time_end   = strtotime($_GET['time_end']);
		$pageSize = empty($_GET['pageSize'])?25:intval($_GET['pageSize']);
		$where = "is_delete=0";

		if(!empty($keyword)) $where .= " AND $fields LIKE '%$keyword%' ";
		if(is_numeric($status)) $where .= " AND status ={$status} ";
		if(is_numeric($payment)) $where .= " AND payment ={$payment} ";
		if(!empty($time_start) && $time_start < ($time_end)) $where .= " AND (add_time BETWEEN {$time_start} AND {$time_end})";
		if(!empty($category_id)) $where .= " AND category_id={$category_id}";
		if(!empty($payment)) $where .= $payment==1? " AND payment =1":" AND payment !=1";//payment=1货到付款，其它为在线支付
		if(!empty($_GET['channel_id'])) $where .= " AND channel_id ='{$_GET['channel_id']}'";
		if(!empty($_GET['user_id'])) $where .= " AND user_id ={$_GET['user_id']}";
		if(!empty($_GET['user_pid'])) $where .= " AND user_pid ={$_GET['user_pid']}";
		if(!empty($_GET['item_id'])) $where .= " AND item_id ={$_GET['item_id']}";
		if(!empty($_GET['referer'])) $where .= " AND referer LIKE '%{$_GET['referer']}%'";
		if(!empty($_GET['mobile'])) $where .= " AND mobile ={$_GET['mobile']}";

		$order = empty($orderby)?"id DESC":"{$orderby} {$sort}";

		switch($this->role){
			case 'admin': 
				$usermap=' AND role="agent"';
			break;
			case 'agent': 
				$usermap= " AND role='member' AND pid={$this->uid}";
				$where .= " AND user_pid ={$this->uid}";
			break;
			case 'member': 
				$usermap=' AND id='.$this->uid;
				$where .= " AND user_id ={$this->uid}";
			break;
		}
		$user = M('User')->where("is_delete=0 ".$usermap)->order('id asc')->select();

		if(isset($_GET['aliziExcel'])){
			header('content-type:text/html;charset=utf8');	
			$aliziConfig = parent::aliziConfig();
			$export = json_decode($aliziConfig['export_order'],true);
			
			$setting = C('setting');
			$options = $setting['export_setting']['export_order']['options'];
			$options = array_intersect_key($options,array_flip($export));
			
			$payments = C('PAYMENT');
			foreach ($payments as $key => $value) { $payment[$key]=$value['name'];}
			$status = C('ORDER_STATUS');//订单状态
			
			$User = M('User');	
			$list  = $Model->field($export)->where($where)->order('id desc')->select();
			$output[] = array_values($options);
			foreach($list as &$li){
				if(in_array('item_extends',$export)){
					$item_extends = json_decode($li['item_extends'],true);
					// var_dump($item_extends);
					$extends = '';
					$extendsArray = array();
					if($item_extends){
						foreach($item_extends as $k=>$v){ 	$extendsArray[] = $k.':'.(is_array($v)?implode('#',$v):$v); }
						$extends = implode("\n",$extendsArray);
					}
				}
				//套餐以及产品
				if(in_array('gift',$export)){
					$gift = json_decode($li['gift'],true);
					
					$gift1 = '';
					$extendsArray = array();
					if($gift){
						foreach($gift as $k=>$v){ 	
						   foreach($v as $k1=>$v1){
							   $extendsArray[] = $k1.':'.(is_array($v1)?implode('#',$v1):$v1); 
						   }
						}
						$gift1 = implode("\n",$extendsArray);
					}
					// var_dump($gift1);
				}
				// die;
				if(in_array('status',$export))$li['status'] = strip_tags($status[$li['status']]);
				if(in_array('payment',$export))$li['payment'] = $payment[$li['payment']];
				if(in_array('gift',$export))$li['gift'] = $gift1;
				if(in_array('item_extends',$export))$li['item_extends'] = $extends;
				if(in_array('add_time',$export))$li['add_time'] = date('Y-m-d H:i:s',$li['add_time']);
				if(in_array('user_pid',$export))$li['user_pid'] = $User->where('id='.$li['user_pid'])->getField('username');
				if(in_array('user_id',$export))$li['user_id'] = $User->where('id='.$li['user_id'])->getField('username');
				if(in_array('address',$export)){
					$li['address'] = $li['address'];
					$li['full_address'] = $li['province'].$li['city'].$li['area'].$li['address'];
					$options['full_address'] = '详细地址';
				}	
			}
			$output = array_merge($output,$list);
	
			if($aliziConfig['export_type']=='csv'){
				csv_export($output);exit;
			}else{
				unset($output[0]);
				parent::aliziExcel($output,$options,date('Y-m-d'));exit;
			}
	    }
		
		//$orders = $Model->query("SELECT id,item_id,item_name,name,mobile,count(id) as num FROM __TABLE__ GROUP BY item_id,mobile");

		import('ORG.Util.Page');
		$count = $Model->where($where)->count();
		$page  = new Page($count,$pageSize);
		$list  = $Model->where($where)->field($field)->limit($page->firstRow . ',' . $page->listRows)->order($order)->select();
		foreach($list as &$li){
			$li['num'] = $Model->where(array("is_delete"=>0,"item_id"=>$li['item_id'],"mobile"=>$li['mobile']))->count();
		}
		$show  = $page->show();
		$category  = M('Category')->order('sort_order desc')->select();
		$status = C('ORDER_STATUS');
		foreach($status as $k=>$v){ 
			$map = "is_delete=0 AND status={$k}";
			if(!empty($payment)) $map .= $payment==1? " AND payment =1":" AND payment !=1";
			switch($this->role){
				case 'agent':  $map .= " AND user_pid ={$this->uid}"; break;
				case 'member':  $map .= " AND user_id ={$this->uid}"; break;
			}
		
			$status[$k] = array('name'=>$v,'count'=>$Model->where($map)->count());
		}

		$this->assign('channel',$channel);
		$this->assign('user',$user);
		$this->assign('category',$category);
		$this->assign('delivery',C('DELIVERY'));
		$this->assign('status',$status);
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->display($this->role);
	}

	function cashOnDelivery(){
		$this->index(1);
	}

	function payOnLine(){
		$this->index(2);
	}
	
	//内容编辑
	function view($id=''){

		$Order = M('Order');
		$where = "id={$id}";
		$info  = $Order->where($where)->find();
		if($this->role=='admin' || ($this->role=='agent' && $info['user_pid']==$this->uid) || ($this->role=='member' && $info['user_id']==$this->uid) ){
			if(!empty($info)) $log = M('OrderLog')->where(array('order_id'=>$info['id']))->order('id asc')->select();
			if(isset($_GET['status'])){
				$map = " AND status=".intval($_GET['status']);
			}
			$pre_id = $Order->where("id<{$info['id']}".$map)->order('id desc')->getField('id');
			$next_id = $Order->where("id>{$info['id']}".$map)->getField('id');

			$aliziConfig = cache('aliziConfig');
			$delivery_setting = array_flip(json_decode($aliziConfig['delivery_setting'],true));
			$delivery = array_intersect_key(C('DELIVERY'),$delivery_setting);
			$this->assign('delivery',$delivery);
			$this->assign('info',$info);
			$this->assign('log',$log);
			$this->assign('pre_id',$pre_id);
			$this->assign('next_id',$next_id);
			$this->display($_GET['do']);
		}else{
			$this->error('无权操作');
		}
	}
	

	function status(){
		
		$id = (int)$_POST['id'];
		$status = (int)$_POST['change_status'];

		$data = array(
			'order_id'=>$id,
			'status'=>$status,
			'user_id'=>(int)$this->uid,
			'remark'=>htmlspecialchars($_POST['action_remark']),
			'delivery_name'=>trim($_POST['delivery_name']),
			'delivery_no'=>trim($_POST['delivery_no']),
		);
		$data['sign'] = createSign($data,C('ALIZI_KEY'));
		
		include("./Home/Lib/Action/ApiAction.class.php");
		R('Api/aliziUpdateStatus',array('data'=>$data));

		//$rs = http($this->aliziHost."index.php?m=Api&a=aliziUpdateStatus", 'POST', array('data'=>$data));

		//$this->ajaxReturn($rs,'操作成功',1);
	}

	//更新快递
	public function deliveryUpdate(){
		$data = array(
			'id'=>(int)$_POST['id'],
			'delivery_name'=>trim($_POST['delivery_name']),
			'delivery_no'=>addslashes($_POST['delivery_no']),
			'update_time'=>time(),
		);
		$rs = M('Order')->save($data);
		if($rs){
			$this->ajaxReturn(null,'保存成功',1);
		}else{
			$this->ajaxReturn(null,'操作失败',0);
		}
		
	}
	public function import(){
		if(IS_POST){
			$status = intval($_POST['status']);
			$delivery_name = trim($_POST['delivery_name']);
			$time = time();
			$excel = array();
			$Public = new PublicAction();
			$Model = M('Order');
			
			if(isset($_POST['upload'])){
				$excelUpload = $Public->upload(true);
				Vendor("PHPExcel.PHPExcel.IOFactory");
				$objPHPExcel = PHPExcel_IOFactory::load("./Public/Uploads".$excelUpload);
				foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
					foreach ($worksheet->getRowIterator() as $row) {
						$cellIterator = $row->getCellIterator();
						$cellIterator->setIterateOnlyExistingCells(false);
						foreach ($cellIterator as $cell) {
							if (!is_null($cell)) {
								//$excel[$cell->getCoordinate()]=$cell->getCalculatedValue();
								$excel[$row->getRowIndex()][]=$cell->getCalculatedValue();
							}
						}
					}
				}
				unset($excel[1]);
				if(count($excel)>0){ $this->ajaxReturn($excel,count($excel),1);}else{$this->ajaxReturn(0,0,0);}
				/*
				foreach($excel as $k=>$v){
					//if($k==1){continue;}
			
					$order_id = $Model->where(array('order_no'=>$v[0]))->getField('id');
			
					if($order_id){
						$data = array('order_id'=>$order_id,'status'=>$status,'remark'=>$v[2],'update_time'=>$time,'user_id'=>$this->uid);
						if($status==3){
							$data['delivery_name']=$delivery_name;
							$data['delivery_no']=$v[1];
						}		

						$data['sign'] = createSign($data,C('ALIZI_KEY'));
						$rs = http($this->aliziHost."index.php?m=Api&a=aliziUpdateStatus", 'POST', array('data'=>$data));
					}
				}
				*/
			}else{
				
				$order_id = $Model->where(array('order_no'=>$_POST['order_no']))->getField('id');
				if($order_id){
					$data = array('order_id'=>$order_id,'status'=>$status,'remark'=>$_POST['remark'],'update_time'=>$time,'user_id'=>$this->uid);
					if($status==3){
						$data['delivery_name']=$delivery_name;
						$data['delivery_no']=$_POST['delivery_no'];
					}		

					$data['sign'] = createSign($data,C('ALIZI_KEY'));
					
					include("./Home/Lib/Action/ApiAction.class.php");
					R('Api/aliziUpdateStatus',array('data'=>$data));
					
					//$rs = http($this->aliziHost."index.php?m=Api&a=aliziUpdateStatus", 'POST', array('data'=>$data));
					//print_r($_POST);print_r($rs);
					$this->ajaxReturn($data,lang('action_success'),1);
				}else{
					$this->ajaxReturn(0,lang('action_失败'),0);
				}
			}
		
			

		}else{
			$status = C('ORDER_STATUS');
			unset($status[0]);
			$this->assign('status',$status);
			$this->assign('delivery',C('DELIVERY'));
			$this->display();
		}
	}
	function modify(){
		if(IS_POST){
			$Model = M('Order');
			if($vo=$Model->create()){
				if(!empty($_POST['item_extends'])){
					$vo['item_extends'] = json_encode($_POST['item_extends']);
				}
				$Model->save($vo);
				//日志记录------------------
				$content= lang('modify_order').',ID:'.$vo['id'];
				$logs=array(
					'types'=>'Order',
					'content'=>$content,
					'username'=>$this->username,
				);
				$this->writeLogs($logs);
				//日志记录------------------
				
				if($_POST['status']!=$_POST['change_status']){
					
					$this->status();
				}
		
				$this->success(lang('modify_success'));
			}else{
				$this->error(lang('modify_failue'));
			}
		}
	}
	
	public function statistics(){
		R('Statistics/index');
	}
	public function channel(){
		R('Statistics/channel');
	}
	public function region(){
		R('Statistics/byRegion',array('start'=>$_GET['start'],'end'=>$_GET['end']));
	}
	public function time(){
		R('Statistics/byTime',array('start'=>$_GET['start'],'end'=>$_GET['end']));
	}
	public function user(){
		R('Statistics/byUser',array('start'=>$_GET['start'],'end'=>$_GET['end']));
	}
	 
	function add(){
	
		$Model = M('Item');
		$keyword = isset($_GET['keyword'])?trim($_GET['keyword']):'';
		$category_id = isset($_GET['category_id'])?intval($_GET['category_id']):0;
		$where = "is_delete=0";
		if(!empty($keyword)) $where .= " AND (name LIKE '%$keyword%'  OR sn='{$keyword}')";
		if(!empty($category_id)) $where .= " AND category_id=".$category_id;
		if($this->role!='admin'){
			$where .= " AND status=1";
			$itemArray= array();
			$itemGroup = M('ItemGroup')->field('item_id')->where(array('group_id'=>$_SESSION['user']['group_id']))->select();
			if($itemGroup){
				 foreach($itemGroup as $li){$itemArray[]=$li['item_id'];}
			}
			$item_id = implode(',',$itemArray);
			$where .= " AND id IN($item_id)";
		}
		
		$order = "sort_order ASC,id DESC";
		
		import('ORG.Util.Page');
		$count = $Model->where($where)->count('distinct(id)');
		$page  = new Page($count,20);
		$list  = $Model->where($where)->limit($page->firstRow . ',' . $page->listRows)->order($order)->select();
		$show  = $page->show();
	
		
		$aliziConfig = cache('aliziConfig');
		foreach ($list as $key => $value) {
			if($aliziConfig['URL_MODEL']==2){
				$url = array(
					'url'=>$this->aliziHost."id/{$value['sn']}.html",
					'order'=>$this->aliziHost."single/{$value['sn']}-{$this->uid}.html",
					'detail'=>$this->aliziHost."detail/{$value['sn']}-{$this->uid}.html",
				);
			}else{
				$url = array(
					'url'=>$this->aliziHost."index.php?m=Index&a=order&id={$value['sn']}",
					'order'=>$this->aliziHost."index.php?m=Order&id={$value['sn']}&uid={$this->uid}",
					'detail'=>$this->aliziHost."index.php?m=Order&id={$value['sn']}&uid={$this->uid}&tpl=detail",
				);
			}
			$list[$key]['url']=$url;
		}

		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->assign('aliziHost',$this->aliziHost);
		$this->display();
	} 
}

